package com.cn.zpark;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @PackageName: com.cn.zpark
 * @ClassName: ServletContextDemo04
 * @Description:
 * @author: RZS
 * @date: 2022/4/8  20:00
 */
@WebServlet("/scd4.do")
public class ServletContextDemo04 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取context对象
        ServletContext context = request.getServletContext();
        // 根据context对象获取绑定的数据
        Integer count = (Integer) context.getAttribute("count");
        // 将拿到的数据+1
        ++ count;
        // 更新绑定数据
        context.setAttribute("count", count);
        // 将访问次数响应到浏览器
        // 设置响应格式
        response.setContentType("text/html;charset=utf-8");
        // 获取写出流对象
        PrintWriter writer = response.getWriter();
        writer.println("<h1>当前网站一共被访问了"+count+"</h1>");
        // 关闭资源
        writer.close();
    }
}
